<?php
namespace app\common\components;

use yii\web\Controller;

/**
 * Class BaseWebController
 * @package app\common\components
 * 集成常用公用方法供所有控制器使用
 */
class BaseWebController extends Controller
{
    public $enableCsrfValidation=false;//关闭csrf

    //获取http中的get参数
    public function get($key,$default_val='')
    {
        return \Yii::$app->request->get($key,$default_val);
    }

    //获取http中的post参数
    public function post($key,$default_val='')
    {
        return \Yii::$app->request->post($key,$default_val);
    }

    //设置cookie的值
    public function setCookie($name,$value,$expire=0)
    {
        $cookie=\Yii::$app->response->cookies;

        $cookie->add(new \yii\web\Cookie([
            'name'=>$name,
            'value'=>$value,
            'expire'=>$expire
        ]));
    }

    //获取cookie值
    public function getCookie($name,$default_val='')
    {
        $cookie=\Yii::$app->request->cookies;

        return $cookie->getValue($name,$default_val);
    }

    //删除cookie
    public function removeCookie($name)
    {
        $cookies=\Yii::$app->response->cookies;
        $cookies->remove($name);
    }

    //api统一返回json格式数据
    public function renderJson($data=[],$msg='ok',$code=200)
    {
        header("Content-Type:application/json");
        echo json_encode([
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data,
            //此次请求的序列号
            'req_id'=>uniqid()
        ]);
    }

    /**
     * @param $msg 提示信息
     * @param $url 跳转的URL
     */
    public function renderJs($msg,$url)
    {
        //@app/views/common/js指定根目录下的路径
        return $this->renderPartial("@app/views/common/js",['msg'=>$msg,'url'=>$url]);
    }
}